//The headers
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "SDL/SDL_ttf.h"
#include <string>
#include <sstream>


//Screen attributes
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int SCREEN_BPP = 32;

//The surfaces
SDL_Surface *background = NULL;
SDL_Surface *startStop = NULL;
SDL_Surface *pauseMessage = NULL;
SDL_Surface *seconds = NULL;
SDL_Surface *screen = NULL;

//The event structure
SDL_Event event;

//The font
TTF_Font *font;

//The color of the font
SDL_Color textColor = { 0, 0, 0 };

//The timer
class Timer{
private:
  //The clock time when the timer started
  int startTicks;

  //The ticks stored when the timer was paused
  int pausedTicks;

  //The timer status
  bool paused;
  bool started;

public:
  //Initializes variables
  Timer();

  //The various clock actions
  void start();
  void stop();
  void pause();
  void unpause();

  //Gets the timer's time
  int get_ticks();

  //Checks the status of the timer
  bool is_started();
  bool is_paused();
};

Timer::Timer()
{
  //Initialize the variables
  startTicks = 0;
  pausedTicks = 0;
  paused = false;
  started = false;
}

void Timer::start()
{
  //Start the timer
  started = true;

  //Unpause the timer
  paused = false;

  //Get current clock time
  startTicks = SDL_GetTicks();
}

void Timer::stop()
{
  //Stop the timer
  started = false;

  //Unpause the timer
  paused = false;
}

int Timer::get_ticks()
{
  //If the timer is running
  if( started == true )
    {
      //If the timer is paused
      if( paused == true )
	{
	  //Return the number of ticks when the timer was paused
	  return pausedTicks;
	}
      else
	{
	  //Return the current time minus the start time
	  return SDL_GetTicks() - startTicks;
	}
    }
  //If the timer isn't running
  return 0;
}

void Timer::pause()
{
  //If the timer is running and isn't already paused
  if( ( started == true ) && ( paused == false ) )
    {
      //Pause the timer
      paused = true;

      //Calculate the paused ticks
      pausedTicks = SDL_GetTicks() - startTicks;
    }
}

void Timer::unpause()
{
  //If the timer is paused
  if( paused == true )
    {
      //Unpause the timer
      paused = false;

      //Reset the starting ticks
      startTicks = SDL_GetTicks() - pausedTicks;

      //Reset the paused Ticks
      pausedTicks = 0;

    }
}

bool Timer::is_started()
{
  return started;
}

bool Timer::is_paused()
{
  return paused;
}

SDL_Surface *load_image( std::string filename )
{
  //The image that's loated
  SDL_Surface *loadedImage = NULL;

  //The opimized surface that will be used
  SDL_Surface *optimizedImage = NULL;

  //Load the image
  loadedImage = IMG_Load( filename.c_str() );

  //If the image loaded
  if( loadedImage != NULL )
    {
      //Create an optimized surface
      optimizedImage = SDL_DisplayFormat( loadedImage );

      //Free the old surface
      SDL_FreeSurface( loadedImage );

      //If the surface was optimized
      if( optimizedImage != NULL )
	{
	  //Color key surface
	  SDL_SetColorKey( optimizedImage, SDL_SRCCOLORKEY, SDL_MapRGB( optimizedImage->format, 0, 0xFF, 0xFF ) );
	}
    }

  //Return the optimized surface
  return optimizedImage;
}

void apply_surface( int x, int y, SDL_Surface *source, SDL_Surface *destination, SDL_Rect *clip = NULL )
{
  //Holds offsets
  SDL_Rect offset;

  //Get offsets
  offset.x = x;
  offset.y = y;

  //Blit
  SDL_BlitSurface( source, clip, destination, &offset );
}

bool init()
{
  //Initialize all SDL subsystems
  if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
    {
      return false;
    }

  //Set up the screen
  screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );

  //I there was an error in setting up the screen
  if( screen == NULL )
    {
      return false;
    }

  //Initialize SDL_ttf
  if( TTF_Init() == -1 )
    {
      return false;
    }

  //Set the window caption
  SDL_WM_SetCaption( "Timer Test", NULL );

  //If everything initialized fine
  return true;
}

bool load_files()
{
  //Load the backgroung image

  background = load_image( "../../media/background.bmp" );

  //Open the font
  font = TTF_OpenFont( "../../../media/fonts/Cash_Font_by_despicablehero.ttf", 24 );

  //If there was a problem in loading the background
  if( background == NULL ) 
    {
      return false;
    }

  //If there was an error in loading the font
  if( font == NULL ) 
    {
      return false;
    }

  //If everything loaded fine
  return true;
}

void clean_up()
{
  //Free the surfaces
  SDL_FreeSurface( background );
  SDL_FreeSurface( startStop );
  SDL_FreeSurface( pauseMessage );

  //Close the font
  TTF_CloseFont( font );

  //Quit SDL_ttf
  TTF_Quit();

  //Quit SDL
  SDL_Quit();
}

int main( int argc, char* argv[] )
{
  //Quit flag
  bool quit = false;

  //Initialize
  if( init() == false )
    {
      return 1;
    }

  //Load the files
  if( load_files() == false )
    {
      return 1;
    }

  //Make the timer
  Timer myTimer;
  
  //Generate the message surfaces
  startStop = TTF_RenderText_Solid( font, "Press S to start or stop the timer", textColor );
  pauseMessage = TTF_RenderText_Solid( font, "Press P to pause or unpause the timer", textColor );

  //Start the timer
  myTimer.start();

  //While the user hasn't quit
  while( quit == false )
    {
      //While there's an event to handle
      while( SDL_PollEvent( &event ) )
	{
	  //If a key was pressed
	  if( event.type == SDL_KEYDOWN )
	    {
	      //If s was pressed
	      if( event.key.keysym.sym == SDLK_s )
		{
		  //If the timer is running
		  if( myTimer.is_started() == true )
		    {
		      //Stop the timer
		      myTimer.stop();
		    }
		  else
		    {
		      //Start the timer
		      myTimer.start();
		    }
		}
	      //If p was presset
	      if( event.key.keysym.sym == SDLK_p )
		{
		  //If the timer is paused
		  if( myTimer.is_paused() == true )
		    {
		      //Unpause the timer
		      myTimer.unpause();
		    }
		  else
		    {
		      //Pause the timer
		      myTimer.pause();
		    }
		}
	    }
	  //If the user has Xed out the window
	  else if( event.type == SDL_QUIT )
	    {
	      //Quit the program
	      quit = true;
	    }
	}

      //Apply the background
      SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0xFF, 0xFF, 0xFF ) );
      //apply_surface( 0, 0, background, screen );

      //Apply the messages
      apply_surface( ( SCREEN_WIDTH - startStop->w ) / 2, 200, startStop, screen);
      apply_surface( ( SCREEN_WIDTH - pauseMessage->w ) / 2, 250, pauseMessage, screen);

      //The timer's time as a string
      std::stringstream time;

      //Convert the timer's time to a string
      //      time << "Timer: " << myTimer.get_ticks() / 1000.f;
      time << myTimer.get_ticks() / 1000.f;

      //Render the time surface
      seconds = TTF_RenderText_Solid( font, time.str().c_str(), textColor );

      //Apply the time surface
      if( seconds != NULL )
	{
	  apply_surface( ( SCREEN_WIDTH - seconds->w ) / 2, 0, seconds, screen );
	}

      //Free the time surface
      SDL_FreeSurface( seconds );

      //Update the screen
      if( SDL_Flip( screen ) == -1 )
	{
	  return 1;
	}
    }

  //Clean up
  clean_up();

  return 0;
}
